/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities.Category;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import factory.DBConnectionFactory;
import entities.Product;
import entities.Tags;
import java.sql.*; 
import java.util.LinkedList;
 
/**
 *
 * @author Garfield
 */
public class MySQLProductDAO extends ProductDAO{
    private Date getCurDate(){
        
        java.util.Date d = new java.util.Date();
        Date date = new Date(d.getYear(), d.getMonth(), d.getDate());
        return date;
    } 
    @Override
    public int getCurId(){
            int ctr=0;
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt2;
        try {
            pstmt2 = conn.prepareStatement("select id from products");
            ResultSet rs=pstmt2.executeQuery();
            while(rs.next())
                ctr=rs.getInt("id");
        } catch (SQLException ex) {
            Logger.getLogger(MySQLUserDAO.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return ctr;
    }
    @Override
    public void addProduct(Product obj) {
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("insert into products(id,name,description,price, imagePic, author, views, dateIn, datePublished) values (?,?,?,?,?,?,?,?,?) ");
            pstmt.setInt(1, getCurId()+1);
            pstmt.setString(2, obj.getName());
            pstmt.setString(3, obj.getDescription());
            pstmt.setDouble(4, obj.getPrice());
            pstmt.setString(5, obj.getImagePic());
            pstmt.setString(6, obj.getAuthor());
            pstmt.setInt(7, 0);  
            pstmt.setDate(8, getCurDate());
            pstmt.setDate(9, obj.getDatePublished());
             pstmt.executeUpdate();
            conn.close();
            DAOFactory myDAOFactory = DAOFactory.getInstance(DAOFactory.MYSQL);
            CategoriesDAO m = myDAOFactory.createCatDAO(); 
            TagsDAO t= myDAOFactory.createTagsDAO();
            int i=0;
            for(Category c: obj.getCs()){
                m.addCatProd(getCurId(), obj.getCs().get(i).getCategoryId());
                i++;
            }
            i=0;
            for(Tags t1: initTags(getCurId())){
                obj.getTags().add(t1);
            }
            
            for(Tags t1: obj.getTags()){
                t.addTags(getCurId(), obj.getTags().get(i).getTags());
                i++;
            }
             
        } catch (SQLException ex) {
            Logger.getLogger(MySQLProductDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public List<Product> findProductByName(String key) {
        try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select * from products where name like ?");
            pstmt.setString(1, "%"+key+"%");
            ResultSet rs = pstmt.executeQuery();
            List<Product> result = new ArrayList<Product>();
            Product oneProduct;
            while (rs.next()){
                
                oneProduct = new Product(); 
                oneProduct.setId(getCurId()+1);
                oneProduct.setName(rs.getString("name"));
                oneProduct.setDescription(rs.getString("description"));
                oneProduct.setPrice(rs.getDouble("price"));
                oneProduct.setImagePic(rs.getString("imagePic"));
                oneProduct.setAuthor(rs.getString("author"));
                oneProduct.setViews(rs.getInt("views"));
                oneProduct.setDateIn(rs.getDate("dateIn"));
                oneProduct.setDatePublished(rs.getDate("datePublished"));
                result.add(oneProduct);
            }
            conn.close();
            return result;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLProductDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public List<Product> sortByCategory(String category) {
         try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select * from products where name like ?");
          //  pstmt.setString(1, "%"+key+"%");
            ResultSet rs = pstmt.executeQuery();
            List<Product> result = new ArrayList<Product>();
            Product oneProduct;
            while (rs.next()){
                
                oneProduct = new Product(); 
                oneProduct.setId(getCurId()+1);
                oneProduct.setName(rs.getString("name"));
                oneProduct.setDescription(rs.getString("description"));
                oneProduct.setPrice(rs.getDouble("price"));
                oneProduct.setImagePic(rs.getString("imagePic"));
                oneProduct.setAuthor(rs.getString("author"));
                oneProduct.setViews(rs.getInt("views"));
                oneProduct.setDateIn(rs.getDate("dateIn"));
                oneProduct.setDatePublished(rs.getDate("datePublished"));
                result.add(oneProduct);
            }
            conn.close();
            return result;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLProductDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
         return null;
    }

    @Override
    public List<Product> sortByName() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> sortByLowestPrice() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> sortByHighestPrice() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> sortByRelevance() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> sortByBestSeller(String category) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> sortByBestSeller() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> viewNewProducts() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> viewNewProducts(String category) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> viewRecentPopularSearches() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> viewRecentProductsViewed() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Product> findProductByName(String key, String category) {
    try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select * from products where name like ? and categoryId like?");
            pstmt.setString(1, "%"+key+"%");
            pstmt.setString(2, "%"+category+"%");

            ResultSet rs = pstmt.executeQuery();
            List<Product> result = new ArrayList<Product>();
            Product oneProduct;
            while (rs.next()){
                oneProduct = new Product();
                oneProduct.setId(rs.getInt("id"));
                oneProduct.setName(rs.getString("name"));
                oneProduct.setDescription(rs.getString("description"));
                oneProduct.setPrice(rs.getFloat("price"));
                result.add(oneProduct);
            }
            conn.close();
            return result;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLProductDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public void editProduct(Product obj) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Product findProductById(int id) {
          try {
            // TODO code application logic here
            DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
            Connection conn = myFactory.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select * from products where '"+id+"'");
             ResultSet rs = pstmt.executeQuery();
             Product oneProduct = new Product();
             while(rs.next()){
                oneProduct.setId(id);
                oneProduct.setName(rs.getString("name"));
                oneProduct.setDescription(rs.getString("description"));
                oneProduct.setPrice(rs.getDouble("price"));
                oneProduct.setImagePic(rs.getString("imagePic"));
                oneProduct.setAuthor(rs.getString("author"));
                oneProduct.setViews(rs.getInt("views"));
                oneProduct.setDateIn(rs.getDate("dateIn"));
                oneProduct.setDatePublished(rs.getDate("datePublished"));
             }
                conn.close();
               return oneProduct;
        } catch (SQLException ex) {
            Logger.getLogger(MySQLProductDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
 
     
    private LinkedList<Tags> initTags(int prodId) {
         
        
        LinkedList<Tags> tags = new LinkedList<Tags>();
        Tags t = new Tags();
        for(String x: findProductById(prodId).getName().split(" ")){
            t= new Tags();
            t.setTags(x);
            t.setBookId(prodId);
            tags.add(t);
            
        }
        for(String x: findProductById(prodId).getAuthor().split(" ")){
         t= new Tags();
            t.setTags(x);
            t.setBookId(prodId);
            tags.add(t);
           
        }
        //series pa:)
        return tags;
        
    }
}
